<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" :content="$t('设置')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <div class="l-rblock" style="overflow: hidden auto">
          <el-tree
            v-loading="treeLoading"
            :data="dataItemTree_ImgType"
            :expand-on-click-node="false"
            node-key="value"
            ref="tree"
            :current-node-key="categoryId"
            @node-click="handleNodeClick"
          >
            <span class="lr-tree-node" slot-scope="{ node }">
              {{ node.label }}
            </span>
          </el-tree>
        </div>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0" class="nobg">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            placeholder="please enter图片名称"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="false" :refreshClick="loadTablePageData">
          <el-button-group>
            <l-upload
              :showFileList="false"
              btnText="添加私有图片"
              :uploadCallback="uploadCallback"
              :limit="1000"
              :isSecretLevel="false"
              accept="image/*"
              @success="
                () => {
                  loadTablePageData();
                }
              "
            ></l-upload>
          </el-button-group>
          <el-button-group>
            <l-upload
              :showFileList="false"
              btnType="success"
              btnText="添加公有图片"
              :uploadCallback="uploadCallbackEX"
              :limit="1000"
              :isSecretLevel="false"
              accept="image/*"
              @success="
                () => {
                  loadTablePageData();
                }
              "
            ></l-upload>
          </el-button-group>
          <el-button-group v-if="multiple">
            <el-button
              @click="confirmImg"
              :disabled="imgList.length == 0"
              size="mini"
              type="warning"
              >{{ $t("选择图片") }}{{ imgList.length }}/9</el-button
            >
          </el-button-group>
        </l-tool-btns>
      </template>
      <div
        class="l-rblock"
        style="padding-bottom: 48px; background-color: #f0f2f5"
        v-loading="tableLoading"
      >
        <div class="l-rblock" style="overflow: hidden auto">
          <div
            @click="selectImg(item)"
            class="l-v-item l-v-item-w"
            v-for="item in tableData"
            :key="item.f_Id"
          >
            <el-image
              fit="contain"
              lazy
              :src="`${apiUrl}system/annexesfile/${item.f_Id}?token=${token}`"
            >
            </el-image>
            <div class="content__main">
              <span class="content__name">{{ item.f_FileName }}</span>
              <div class="content__menulist">
                <div class="content__view">
                  <el-tooltip content="Delete">
                    <i
                      class="el-icon-delete"
                      @click.stop="handleDelete(item)"
                    ></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
            <div v-if="isSelectImg(item)" class="l-img-mask">
              <span v-if="multiple">{{ getImgNum(item) }}</span>
            </div>
          </div>
        </div>
        <div class="l-table--pagination" style="border: 0">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            background
            small
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-size="tablePageSize"
            :current-page.sync="tableCurrentPage"
            :total="tableTotal"
          >
          </el-pagination>
        </div>
      </div>
    </l-panel>

    <l-drawer
      :title="$t('分类管理')"
      :visible.sync="classifysVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <l-dataitem-index classifyCode="ImgType"></l-dataitem-index>
    </l-drawer>
  </l-layout>
</template>
<script>
const api = window.$api.system.img;
export default {
  name: "l-img-space",
  props:{
    multiple:{
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      //query
      searchWord: "",

      categoryId: "learun_img",
      treeLoading: true,

      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tablePageSize: 20,
      tableCurrentPage: 1,

      classifysVisible: false,

      imgList: [],
    };
  },
  computed: {
    dataItemTree_ImgType() {
      let data = [
        {
          f_Id: "learun_img",
          f_ParentId: "0",
          f_ItemValue: "learun_img",
          f_ItemName: "全部图片",
          f_EnabledMark: 1,
        },
      ];
      data.push(...(this.lr_dataItem["ImgType"] || []));
      return this.lr_dataItemTree(data);
    },
  },
  async created() {
    await this.lr_loadDataItem("ImgType");
    this.treeLoading = false;
    this.loadTablePageData();
  },
  methods: {
    handleSettingClick() {
      this.classifysVisible = true;
    },

    handleNodeClick(data) {
      this.categoryId = data.value;
      this.loadTablePageData();
    },

    hanleSearch() {
      this.loadTablePageData();
    },

    handleCurrentChange(val) {
      this.tableCurrentPage = val;
      this.loadTablePageData(true);
    },
    handleSizeChange(val) {
      this.tablePageSize = val;
      this.loadTablePageData(true);
    },
    async loadTablePageData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate DESC,F_FileName",
        f_FileName: this.searchWord,
        f_FileType: this.categoryId == "learun_img" ? "" : this.categoryId,
      };
      const data = await this.$awaitWraper(api.getPage(queryData));
      if (data) {
        this.tableData = data.rows;
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
        this.tableTotal = 0;
      }
      this.tableLoading = false;
    },
    handleDelete(row) {
      this.$confirm(this.$t("此操作将永久Delete, 是否继续?"), this.$t("Tips"), {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning",
      })
        .then(async () => {
          const res = await this.$awaitWraper(api.remove(row.f_Id));
          if (res) {
            this.$message({
              type: "success",
              message: "Delete  success",
            });
            this.loadTablePageData(this.tableData.length == 1 ? false : true);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled"),
          });
        });
    },
    uploadCallback(data) {
      return api.upload(this.categoryId, data);
    },
    uploadCallbackEX(data) {
      data.isPublic = 1;
      return api.upload(this.categoryId, data);
    },

    selectImg(item) {
      if (this.multiple) {
        if (this.isSelectImg(item)) {
          this.imgList.splice(this.getImgNum(item) - 1, 1);
        } else {
          if (this.imgList.length < 9) {
            this.imgList.push(item);
          }
        }
      }
      else{
        this.$emit("confirm", [item]);
      }
    },
    isSelectImg(item) {
      return this.imgList.findIndex((t) => t.f_Id == item.f_Id) > -1;
    },
    getImgNum(item) {
      return this.imgList.findIndex((t) => t.f_Id == item.f_Id) + 1;
    },

    confirmImg() {
      this.$emit("confirm", this.imgList);
      this.imgList = [];
    },
  },
};
</script>
<style>
.nobg .l-panel--tool {
  background: #fff;
  border: 0;
}
</style>